<?php
namespace app\modules\backend\controllers;


use app\models\Shop;
use app\models\Good;
use app\models\Area;
use app\models\Message;
use app\models\Customer;
use app\tools\WxPay;
use app\tools\Re;
use app\tools\Qiniu;
use app\models\OrderInfo;
use app\models\CashOutRecord;
use Yii;

class FinanceController extends BaseController
{
  public $state_name_arr = ['待支付','已支付','待退款','已退款','退款失败','服务中','已完成'];
  public $cash_state_name_arr = ['待审核','提现成功','提现失败'];
    
  //平台/门店订单统计
  public function actionOrderStatistics() {
    $shop_id = Yii::$app->request->post('shop_id', 0);
    $money_order_all_query = OrderInfo::find()->where(['order_type' => 1, 'state' => [1,2,4,5,6]]);//订单到款总金额
    $money_order_ky_query = OrderInfo::find()->where(['order_type' => 1, 'state' => 6]);//可提现金额
    $money_order_djs_query = OrderInfo::find()->where(['order_type' => 1, 'state' => [1,2,4,5]]);//待结算金额
    $money_order_cashing_query = CashOutRecord::find()->where(['audit_state' => 0]);//提现中金额
    $money_order_cashed_query = CashOutRecord::find()->where(['audit_state' => 1]);//提现成功金额
    if (Yii::$app->user->identity->shop_id) {//门店人员只读取本门店数据
      $shop_id = Yii::$app->user->identity->shop_id;
    }
    if($shop_id) {
      $money_order_all_query->andWhere(['shop_id' => $shop_id]);
      $money_order_ky_query->andWhere(['shop_id' => $shop_id]);
      $money_order_djs_query->andWhere(['shop_id' => $shop_id]);
      $money_order_cashing_query->andWhere(['shop_id' => $shop_id]);
      $money_order_cashed_query->andWhere(['shop_id' => $shop_id]);
    }
    $money_order_all = $money_order_all_query->SUM('money');
    $money_order_all = is_numeric($money_order_all) ? $money_order_all : 0;
    
    $money_order_ky = $money_order_ky_query->SUM('money');
    $money_order_ky = is_numeric($money_order_ky) ? $money_order_ky : 0;

    $money_order_djs = $money_order_djs_query->SUM('money');
    $money_order_djs = is_numeric($money_order_djs) ? $money_order_djs : 0;
    
    $money_order_cashing = $money_order_cashing_query->SUM('money');
    $money_order_cashing = is_numeric($money_order_cashing) ? $money_order_cashing : 0;
    
    $money_order_cashed = $money_order_cashed_query->SUM('money_origin');
    $money_order_cashed = is_numeric($money_order_cashed) ? $money_order_cashed : 0;

    //门店可用金额 = 门店订单到账总金额-提现成功金额-提现中的金额
    $money_order_ky = bcsub($money_order_ky, $money_order_cashing, '2');
    $user_money_ky = bcsub($money_order_ky, $money_order_cashed, '2');

    $data = [
      'money_order_all' => floatval($money_order_all),
      'money_order_djs' => floatval($money_order_djs),
      'money_order_cashing' => floatval($money_order_cashing),
      'money_order_ky' => floatval($money_order_ky),
    ];
    return Re::data(['data' => $data]);
  }

  //平台/门店账单明细
  public function actionOrderRecord() {
    $page = Yii::$app->request->post('page', 0);
    $page_size = Yii::$app->request->post('page_size', 20);
    $shop_id = Yii::$app->request->post('shop_id', 0);
    $name = Yii::$app->request->post('name', '');
    $phone = Yii::$app->request->post('phone', '');
    $area_id = Yii::$app->request->post('area_id', 0);
    $date_range = Yii::$app->request->post('date_range', '');
    $query = OrderInfo::find()
      ->leftJoin(Shop::tableName(), 'order_info.shop_id = shop.id')
      ->leftJoin(Customer::tableName(), 'order_info.customer_id = customer.id')
      ->where("(order_type = 1 and state > 0) OR (order_type = 2 and refund_audit_state = 1 )");
    if (Yii::$app->user->identity->shop_id) {//门店人员只读取本门店数据
      $query->andWhere(['order_info.shop_id' => Yii::$app->user->identity->shop_id]);
    }
    if ($shop_id) {
      $query->andWhere(['order_info.shop_id' => $shop_id]);
    }
    if ($name) {
      $query->andWhere(['like', 'customer.name', $name]);
    }
    if ($phone) {
      $query->andWhere(['like', 'customer.phone', $phone]);
    }
    if ($area_id) {
      $query->andWhere(['shop.area_id' => $area_id]);
    }
    if ($date_range) {
      $data_arr = explode("-", $date_range);
      $start_at = $data_arr[0];
      $end_at = $data_arr[1];
      $query->andWhere("order_info.created_at >= '$start_at' and order_info.created_at <= '$end_at'");
    }
    $list = $query->orderBy('order_info.created_at desc')->limit($page_size)->offset($page_size*$page)->all();
    $data = [];
    if ($list) {
      foreach ($list as $v) {
        $data[] = [
          'id' => $v->id,
          'shop_id' => $v->shop_id,
          'shop_name' => $v->shop->name,
          'name' => $v->customer->name,
          'phone' => $v->customer->phone,
          'good_name' => $v->good->name,
          'order_sn' => $v->order_sn,
          'order_type' => $v->order_type,
          'created_time' => date("Y-m-d H:i:s", $v->created_at),
          'money' => floatval($v->money),
          'moneys' => ($v->order_type == 1 ? '+' : '-') . floatval($v->money)
        ];
      }
    }
    return Re::data([
      'data' => $data,
      'totalPage' => $query->count(),
      'currentPage' => $page,
      'perPage' => OrderInfo::PAGE_SIZE
    ]);
  }

  //门店最新提现的信息
  public function actionNewCashInfo() {
    $shop_id = Yii::$app->request->post('shop_id', 0);
    $data = CashOutRecord::find()
      ->select(['bank_account', 'account', 'bank', 'bank_address', 'name', 'phone'])
      ->where(['shop_id' => $shop_id])
      ->orderBy('id desc')
      ->one();
    $data = $data ?: [];
    return Re::data(['data' => $data]);
  }

  //门店发起提现
  public function actionAddCash() {
    $shop_id = Yii::$app->request->post('shop_id', 0);
    $bank_account = Yii::$app->request->post('bank_account', '');
    $account = Yii::$app->request->post('account', '');
    $bank = Yii::$app->request->post('bank', '');
    $bank_address = Yii::$app->request->post('bank_address', '');
    $name = Yii::$app->request->post('name', '');
    $phone = Yii::$app->request->post('phone', '');
    $receipt_js = Yii::$app->request->post('receipt_js', '');
    $money_origin = Yii::$app->request->post('money_origin', 0);
    $money_wx = Yii::$app->request->post('money_wx', 0);
    $money_yj = Yii::$app->request->post('money_yj', 0);
    $money = Yii::$app->request->post('money', 0);
    $cash_out_record = new CashOutRecord();
    $cash_out_record->shop_id = $shop_id;
    $cash_out_record->admin_id = Yii::$app->user->id;
    $cash_out_record->money_origin = $money_origin;
    $cash_out_record->money_wx = $money_wx;
    $cash_out_record->money_yj = $money_yj;
    $cash_out_record->money = $money;
    $cash_out_record->bank_account = $bank_account;
    $cash_out_record->account = $account;
    $cash_out_record->bank = $bank;
    $cash_out_record->bank_address = $bank_address;
    $cash_out_record->name = $name;
    $cash_out_record->phone = $phone;
    $cash_out_record->receipt_js = $receipt_js;
    $cash_out_record->audit_state = 0;
    $cash_out_record->created_at = time();
    if (!$cash_out_record->save()) {
      return Re::data(null, $cash_out_record->showErrors(), Re::ERROR);
    }
    return Re::data();
  }

  //门店提现记录
  public function actionCashList() {
    $page = Yii::$app->request->post('page', 0);
    $page_size = Yii::$app->request->post('page_size', 20);
    $shop_id = Yii::$app->request->post('shop_id', 0);
    $name = Yii::$app->request->post('name', '');
    $phone = Yii::$app->request->post('phone', '');
    $audit_state = Yii::$app->request->post('audit_state', -1);
    $date_range = Yii::$app->request->post('date_range', '');
    $query = CashOutRecord::find()
      ->where(['status' => 1]);
    if (Yii::$app->user->identity->shop_id) {//门店人员只读取本门店数据
      $shop_id = Yii::$app->user->identity->shop_id;
    }
    if ($shop_id) {
      $query->andWhere(['shop_id' => $shop_id]);
    }
    if ($audit_state > -1) {
      $query->andWhere(['audit_state' => $audit_state]);
    }
    if ($name) {
      $query->andWhere(['like', 'name' => $name]);
    }
    if ($phone) {
      $query->andWhere(['like', 'phone' => $phone]);
    }
    if ($date_range) {
      $data_arr = explode("-", $date_range);
      $start_at = $data_arr[0];
      $end_at = $data_arr[1];
      $query->andWhere("cash_out_record.created_at >= '$start_at' and cash_out_record.created_at <= '$end_at'");
    }
    $list = $query->orderBy('cash_out_record.created_at desc')->limit($page_size)->offset($page_size*$page)->all();
    $data = [];
    if ($list) {
      foreach ($list as $v) {
        $data[] = [
          'id' => $v->id,
          'bank_account' => $v->bank_account,
          'account' => $v->account,
          'bank' => $v->bank,
          'bank_address' => $v->bank_address,
          'name' => $v->name,
          'phone' => $v->phone,
          'money_origin' => $v->money_origin,
          'money_wx' => $v->money_wx,
          'money_yj' => $v->money_yj,
          'money' => $v->money,
          'receipt_js' => $v->receipt_js,
          'receipt_dk' => $v->receipt_dk,
          'created_time' => date("Y-m-d H:i:s", $v->created_at),
          'remark' => $v->remark,
          'audit_state' => $v->audit_state,
          'audit_state_name' => $this->cash_state_name_arr[$v->audit_state],
          'audit_remark' => $v->audit_remark,
          'audit_time' => $v->audit_at ? date("Y-m-d H:i:s", $v->audit_at) : '',
        ];
      }
    }
    return Re::data([
      'data' => $data,
      'totalPage' => $query->count(),
      'currentPage' => $page,
      'perPage' => CashOutRecord::PAGE_SIZE
    ]);
  }

  //门店提现审核
  public function actionAuditCash(){
    $id = Yii::$app->request->post('id', 0);
    $audit_state = Yii::$app->request->post('audit_state', 1);
    $audit_remark = Yii::$app->request->post('audit_remark', '');
    $receipt_dk = Yii::$app->request->post('receipt_dk', '');
    $cash_out_record = CashOutRecord::findOne($id);
    if (empty($cash_out_record)) {
      return Re::data(null, '提现信息读取失败', Re::ERROR);
    }
    $cash_out_record->audit_state = $audit_state;
    $cash_out_record->audit_remark = $audit_remark;
    $cash_out_record->receipt_dk = $receipt_dk;
    $cash_out_record->audit_at = time();
    $cash_out_record->save();
    return Re::data();
  }

  public function actionGetJsTemp(){
    require_once '../vendor/phpoffice/phpexcel/Classes/PHPExcel/IOFactory.php';
    require_once '../vendor/phpoffice/phpexcel/Classes/PHPExcel.php';
    require_once '../vendor/phpoffice/phpexcel/Classes/PHPExcel/Writer/Excel2007.php';
    $shop_id = Yii::$app->request->post('shop_id', 0);
    $bank_account = Yii::$app->request->post('bank_account', '');
    $account = Yii::$app->request->post('account', '');
    $bank = Yii::$app->request->post('bank', '');
    $bank_address = Yii::$app->request->post('bank_address', '');
    $name = Yii::$app->request->post('name', '');
    $phone = Yii::$app->request->post('phone', '');
    $remark = Yii::$app->request->post('remark', '');
    $wx_pre = Yii::$app->params['wx_pre'];
    $template = getcwd().'/public/js_file/js_temp.xlsx';
    $objPHPExcel = \PHPExcel_IOFactory::load($template);
    //$objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); //下面的用法就能解决
    $shop_info = Shop::findOne($shop_id);
    $money_ky = OrderInfo::find()->where(['shop_id' => $shop_id, 'order_type' => 1, 'state' => 6])->SUM('money');//订单到款总金额
    $money_kc_wx = $money_ky * $wx_pre < 0.01 ? 0.01 : $money_ky * $wx_pre;
    $money_kc_yj = ($money_ky * $shop_info->commission_pre/100 > 0 && $money_ky * $shop_info->commission_pre/100 < 0.01) ? 0.01 : $money_ky * $shop_info->commission_pre/100;
    $money_kc_all = $money_kc_wx + $money_kc_yj;
    $money_cash = $money_ky - $money_kc_all;
    $money_cash = number_format($money_cash, 2);
    $title = "[".$shop_info->name."]收支汇总结算函";
    $wx_pre_str = "腾讯官方手续费（".($wx_pre*100)."%）";
    $money_cash_str = "此次收款总额减去已退款项，扣除手续费后，实际应汇给企业金额为：¥ ".$money_cash." 元。";
    $name_str = "联系人: ".$name;
    $phone_str = "联系电话: ".$phone;
    $bank_account_str = "账户名称: ".$bank_account;
    $bank_str = "开户行: ".$bank."(".$bank_address.")";
    $account_str = "收款账号: ".$account;
    $remark_str = "备注: ".$remark;
    //接下来就是写数据到表格里面去  
    $objActSheet = $objPHPExcel->getActiveSheet();  
    $objActSheet->setCellValue('B1',  $title);//标题
    $objActSheet->setCellValue('E3',  $money_ky);//订单总金额
    $objActSheet->setCellValue('B5',  $wx_pre_str);//微信手续费文案
    $objActSheet->setCellValue('E5',  $money_kc_wx);//微信手续费率
    $objActSheet->setCellValue('E6',  $money_kc_yj);//佣金
    $objActSheet->setCellValue('E7',  $money_kc_all);//扣除总金额
    $objActSheet->setCellValue('E8',  $money_cash);//实际汇给企业金额
    $objActSheet->setCellValue('B10',  $money_cash_str);//联系人
    $objActSheet->setCellValue('B14',  $name_str);//联系人
    $objActSheet->setCellValue('D14',  $phone_str);//联系电话
    $objActSheet->setCellValue('B15',  $bank_str);//开户行
    $objActSheet->setCellValue('B16',  $bank_account_str);//账户名称
    $objActSheet->setCellValue('B17',  $account_str);//收款账号
    $objActSheet->setCellValue('B18',  $remark_str);//备注
    $file_name = "结算函_".$shop_info->name.'.xlsx';
    //本地保存
    $local_file_path = './public/js_file/'.$file_name;
    $objWriter->save($local_file_path);
    $res = Qiniu::putFileToQiniu($local_file_path);
    $file_path = $res['domain'].$res['key'].'?attname='.$file_name;
    return Re::data(['file' => $file_path]);
  }
}
